import { create } from 'zustand';
import { devtools } from 'zustand/middleware';

type Theme = 'light' | 'dark' | 'system';

interface ThemeStore {
  theme: Theme;
  systemTheme: 'light' | 'dark';
  isDark: boolean;
  
  // 操作方法
  setTheme: (theme: Theme) => void;
  setSystemTheme: (theme: 'light' | 'dark') => void;
  toggleTheme: () => void;
  
  // 工具方法
  initializeTheme: () => void;
  applyTheme: (theme: Theme) => void;
}

// 获取系统主题
const getSystemTheme = (): 'light' | 'dark' => {
  return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
};

// 监听系统主题变化
const watchSystemTheme = (callback: (theme: 'light' | 'dark') => void) => {
  const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
  const handler = (e: MediaQueryListEvent) => {
    callback(e.matches ? 'dark' : 'light');
  };
  
  if (mediaQuery.addEventListener) {
    mediaQuery.addEventListener('change', handler);
  } else {
    mediaQuery.addListener(handler);
  }
  
  return () => {
    if (mediaQuery.removeEventListener) {
      mediaQuery.removeEventListener('change', handler);
    } else {
      mediaQuery.removeListener(handler);
    }
  };
};

export const useThemeStore = create<ThemeStore>()(
  devtools(
    (set, get) => ({
      theme: (localStorage.getItem('theme') as Theme) || 'system',
      systemTheme: getSystemTheme(),
      isDark: false,

      // 设置主题
      setTheme: (theme) => {
        set({ theme });
        localStorage.setItem('theme', theme);
        get().applyTheme(theme);
      },

      // 设置系统主题
      setSystemTheme: (systemTheme) => {
        const { theme } = get();
        const isDark = theme === 'system' ? systemTheme === 'dark' : theme === 'dark';
        set({ systemTheme, isDark });
      },

      // 切换主题
      toggleTheme: () => {
        const { theme } = get();
        const newTheme = theme === 'light' ? 'dark' : 'light';
        get().setTheme(newTheme);
      },

      // 初始化主题
      initializeTheme: () => {
        const theme = (localStorage.getItem('theme') as Theme) || 'system';
        const systemTheme = getSystemTheme();
        const isDark = theme === 'system' ? systemTheme === 'dark' : theme === 'dark';
        
        set({ theme, systemTheme, isDark });
        get().applyTheme(theme);
        
        // 监听系统主题变化
        watchSystemTheme((newSystemTheme) => {
          get().setSystemTheme(newSystemTheme);
        });
      },

      // 应用主题到DOM
      applyTheme: (theme) => {
        const root = document.documentElement;
        const systemTheme = getSystemTheme();
        const isDark = theme === 'system' ? systemTheme === 'dark' : theme === 'dark';
        
        if (isDark) {
          root.classList.add('dark');
          root.classList.remove('light');
          root.style.setProperty('--bg-color', '#0a0a0a');
          root.style.setProperty('--text-color', 'rgba(255, 255, 255, 0.87)');
        } else {
          root.classList.add('light');
          root.classList.remove('dark');
          root.style.setProperty('--bg-color', '#ffffff');
          root.style.setProperty('--text-color', '#213547');
        }
        
        // 更新MUI主题
        if (window.dispatchEvent) {
          window.dispatchEvent(new CustomEvent('themeChange', { detail: { theme, isDark } }));
        }
      },
    }),
    {
      name: 'theme-store',
    }
  )
);

// 选择器
export const useTheme = () => useThemeStore(state => state.theme);
export const useIsDark = () => useThemeStore(state => state.isDark);
export const useSystemTheme = () => useThemeStore(state => state.systemTheme);

// 初始化主题
export const initializeTheme = () => {
  useThemeStore.getState().initializeTheme();
};